'use strict';

const db = uniCloud.database();

async function checkLevelUp(userId) {
  if (!userId) return;

  try {
    const userRes = await db.collection('users').doc(userId).field({ 'points': 1, 'level': 1 }).get();
    if (!userRes.data || userRes.data.length === 0) {
      console.error(`[checkLevelUp] User not found: ${userId}`);
      return;
    }

    const user = userRes.data[0];
    const userPoints = user.points || 0;
    const currentLevel = user.level;
    
    // 简化版本：使用固定的等级配置
    const levels = [
      { "name": "健康分享者", "points_required": 0, "commission_rate": 0.10 },
      { "name": "推广大使", "points_required": 100, "commission_rate": 0.15 },
      { "name": "区域代理", "points_required": 500, "commission_rate": 0.20 }
    ];
    const sortedLevels = [...levels].sort((a, b) => b.points_required - a.points_required);

    let newLevel = '健康分享者'; // Default level
    for (const level of sortedLevels) {
      if (userPoints >= level.points_required) {
        newLevel = level.name;
        break;
      }
    }

    if (newLevel !== currentLevel) {
      await db.collection('users').doc(userId).update({
        level: newLevel
      });
      console.log(`用户 ${userId} 已成功升级到 ${newLevel}`);
    }

  } catch (e) {
    console.error(`[checkLevelUp] Error for user ${userId}:`, e);
  }
}

// 导入 pointsLogger
const { logPointChange } = require('./pointsLogger');

module.exports = {
  checkLevelUp,
  logPointChange
};
